package com.zx.web.servelt;

import cn.dsna.util.images.ValidateCode;
import com.alibaba.druid.util.StringUtils;
import com.zx.bean.Address;
import com.zx.bean.User;
import com.zx.web.service.AddressService;
import com.zx.web.service.UserService;
import com.zx.web.service.impl.AddressServiceImpl;
import com.zx.web.service.impl.UserServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author 章鑫
 * @version V1.0
 * @Project 2022-09-05
 * @Package com.zx.web.servelt
 * @Description:
 * @Date 2022/9/13 10:52
 */
@WebServlet("/userservlet")
public class UserServlet extends BaseServlet{
//    public void login(HttpServletRequest req, HttpServletResponse resp){
//        System.out.println("login");
//    }
//    public void register(HttpServletRequest req, HttpServletResponse resp){
//        System.out.println("register");
//    }
//    public void logout(HttpServletRequest req, HttpServletResponse resp){
//        System.out.println("logout");
//    }

    UserService service = new UserServiceImpl();
    AddressService addressService = new AddressServiceImpl();

    /**
     * 设为默认
     * @param req
     * @param resp
     * @return
     */
    public String defaultAddress(HttpServletRequest req,HttpServletResponse resp){
        int id = Integer.parseInt(req.getParameter("id"));
        //获取uid
        User user = (User) req.getSession().getAttribute("user");
        int userId = user.getId();

        addressService.setDefaultAddress(id,userId);

//        //查找address表中uid的地址中有无level是否为0的
//        Address address = addressService.findAddressLevel(userId);
//        if(address!=null) {
//            //如果有，修改查到的level为0
//            address.setLevel(0);
//            addressService.updateAddress(address);
//        }
//        //修改id的level
//        addressService.updateAddressLevel(id);
        return "redirect:/userservlet?method=getAddress";
    }

    /**
     * 修改地址
     * @param req
     * @param resp
     * @return
     */
    public String updateAddress(HttpServletRequest req,HttpServletResponse resp){

        //获取地址id
        int id = Integer.parseInt(req.getParameter("id"));

        String name = req.getParameter("name");
        String phone = req.getParameter("phone");
        String detail = req.getParameter("detail");

        Address address = new Address();
        address.setId(id);
        address.setName(name);
        address.setPhone(phone);
        address.setDetail(detail);
        address.setLevel(0);

        addressService.updateAddress(address);

        return "redirect:/userservlet?method=getAddress";
    }

    /**
     * 删除地址
     * @param req
     * @param resp
     * @return
     */
    public String deleteAddress(HttpServletRequest req,HttpServletResponse resp){

        //获取地址id
        int id = Integer.parseInt(req.getParameter("id"));

        addressService.deleteAddress(id);

        return "redirect:/userservlet?method=getAddress";
    }

    /**
     * 添加地址
     * @param req
     * @param resp
     */
    public String addAddress(HttpServletRequest req,HttpServletResponse resp){
        //获取数据
        String name = req.getParameter("name");
        String phone = req.getParameter("phone");
        String detail = req.getParameter("detail");
        //获取uid
        User user = (User) req.getSession().getAttribute("user");
        int userId = user.getId();

        Address address = new Address();
        address.setName(name);
        address.setDetail(detail);
        address.setPhone(phone);
        address.setLevel(0);
        address.setUid(userId);

        addressService.addAddress(address);

        return "redirect:/userservlet?method=getAddress";
    }

    /**
     * 获取地址
     * @param req
     * @param resp
     * @return
     */
    public String getAddress(HttpServletRequest req,HttpServletResponse resp){
        User user = (User) req.getSession().getAttribute("user");
        int userId = user.getId();

        List<Address> addList = addressService.getAddressByUid(userId);
        req.setAttribute("addList",addList);
        return "forward:/self_info.jsp";
    }

    /**
     * 注销
     * @param req
     * @param resp
     */
    public String logOut(HttpServletRequest req, HttpServletResponse resp){
        req.getSession().invalidate();
        return "redirect:/login.jsp";
    }

    /**
     * 登录模块
     *      成功 跳转到index.jsp
     *      失败 跳转到login.jsp
     * @param req
     * @param resp
     */
    public String login(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        User user = service.login(username,password);
        if(user!=null){
            String auto = req.getParameter("auto");
            if("on".equalsIgnoreCase(auto)){
                String encode = URLEncoder.encode(username+"#"+password,"utf-8");
                Cookie cookie = new Cookie("user",encode);
                cookie.setDomain("localhost");
                cookie.setMaxAge(14*24*60*60);
                cookie.setPath("/");
                resp.addCookie(cookie);
            }

            req.getSession().setAttribute("user",user);
            return "redirect:/index.jsp";
        }else{
            return "redirect:/login.jsp";
        }

    }

    /**
     * 生成验证码
     * @param req
     * @param resp
     */
    public void code(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        ValidateCode validateCode = new ValidateCode(120,40,2,50);

        //获取生成的验证码
        String code = validateCode.getCode();
        //存入session
        req.getSession().setAttribute("code",code);

        validateCode.write(resp.getOutputStream());
    }

    /**
     * 校验验证码
     * @param req
     * @param resp
     * @throws IOException
     */
    public void checkCode(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String codeInput = req.getParameter("code");
        Object code = req.getSession().getAttribute("code");

        PrintWriter writer = resp.getWriter();
        if(code!=null){
            String codeSession = (String) code;
            if(codeSession.equalsIgnoreCase(codeInput)){
                writer.write("0");
            }else{
                writer.write("1");
            }
        }else{
            writer.write("1");
        }
    }

    /**
     * 注册模块
     *    成功  跳转login.jsp
     *    失败  跳转register.jsp
     * @param req
     * @param resp
     * @return
     */
    public String register(HttpServletRequest req, HttpServletResponse resp){
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        String gender = req.getParameter("gender");
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setEmail(email);
        user.setGender(gender);
        boolean result = service.register(user);
        if(result){
            return "redirect:/login.jsp";
        }else{
            return "redirect:/register.jsp";
        }

    }

    /**
     * 对用户名进行校验
     *      用户名为空    返回0
     *      用户名已存在  返回1
     *      用户名可用    返回2
     * @param req
     * @param resp
     */
    public void checkUserName(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String username = req.getParameter("username");
        PrintWriter writer = resp.getWriter();
        if(StringUtils.isEmpty(username)){
            writer.write("0");
        }else{
            User user = service.findByUserName(username);
            if(user!=null){
                writer.write("1");
            }else{
                writer.write("2");
            }

        }
    }
}
